package com.wangshuile.vue.commons.exception;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import com.wangshuile.vue.commons.bean.CodeMsg;
import com.wangshuile.vue.commons.bean.Result;

/**
 * 全局异常请求体统一返回类
 *
 * @author liqiaofei
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return Result.error(ex.getCm());
        } else if (e instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException ex = (MissingServletRequestParameterException) e;
            return Result.errorMsg("参数 " + ex.getParameterName() + " 不能为空");
        } else if (e instanceof MethodArgumentTypeMismatchException) {
            return Result.error(CodeMsg.METHOD_ARG_TYPE_EXCEPTION);
        } else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            FieldError fieldError = ex.getBindingResult().getFieldErrors().get(0);
            return Result.errorMsg(fieldError.getField() + fieldError.getDefaultMessage());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            return Result.errorMsg(e.getMessage());
        } else if (e instanceof EmptyResultDataAccessException) {
            return Result.error(CodeMsg.DATA_EMPLY);
        } else {
            logger.error("exceptionHandler(): ", e);
        }
        return Result.error(CodeMsg.SERVER_EXCEPTION);
    }
}
